package com.example.myapplication.ui;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.SearchView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.myapplication.MainActivity;
import com.example.myapplication.adapter.TodoAdapter;
import com.example.myapplication.database.TodoDatabaseHelper;
import com.example.myapplication.databinding.ActivityTodoBinding;
import com.example.myapplication.databinding.DialogAddTodoBinding;
import com.example.myapplication.model.Todo;
import com.example.myapplication.utils.ReminderBroadcastReceiver;
import com.example.myapplication.utils.TimeUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TodoActivity extends AppCompatActivity {
    private ActivityTodoBinding binding;
    private TodoDatabaseHelper databaseHelper;
    private TodoAdapter todoAdapter;
    private List<Todo> todoList = new ArrayList<>();
    private long reminderTime = -1;  // 默认不设置提醒

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTodoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 初始化数据库
        databaseHelper = new TodoDatabaseHelper(this);

        // 初始化 RecyclerView 和 Adapter
        todoAdapter = new TodoAdapter(todoList, databaseHelper, this::loadTodoList);
        binding.listRv.setLayoutManager(new LinearLayoutManager(this));
        binding.listRv.setAdapter(todoAdapter);

        // 加载待办事项
        loadTodoList();

        // 搜索功能
        binding.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false; // 不处理提交
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // 根据输入文本动态更新待办事项列表
                filterTodoList(newText);
                return true;
            }
        });

        // 点击加号添加新待办事项
        binding.addIv.setOnClickListener(view -> showAddTodoDialog());

        // 切换页面
        binding.shiftIv.setOnClickListener(view -> {
            Intent intent = new Intent(TodoActivity.this, MainActivity.class);
            startActivity(intent);
        });
    }

    // 加载待办事项列表
    private void loadTodoList() {
        try {
            todoList.clear();
            List<Todo> allTodos = databaseHelper.getAllTodos();

            // 按未完成优先排序，假设 Todo 有 isCompleted 属性
            Collections.sort(allTodos, new Comparator<Todo>() {
                @Override
                public int compare(Todo o1, Todo o2) {
                    // 使用 Boolean.compare，未完成优先
                    return Boolean.compare(o1.isCompleted(), o2.isCompleted());
                }
            });

            todoList.addAll(allTodos);
            todoAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            Log.e("TodoActivity", "Error loading todo list", e);
            // 使用 Handler 延迟显示 Toast
            new Handler(getMainLooper()).post(() ->
                    Toast.makeText(this, "加载待办事项失败：" + e.getMessage(), Toast.LENGTH_SHORT).show()
            );
        }
    }

    // 根据查询文本过滤待办事项
    private void filterTodoList(String query) {
        List<Todo> filteredList = new ArrayList<>();
        for (Todo todo : todoList) {
            if (todo.getTask().toLowerCase().contains(query.toLowerCase())) {
                filteredList.add(todo);
            }
        }
        todoAdapter.updateTodoList(filteredList); // 更新适配器
    }

    // 显示添加待办事项的对话框
    private void showAddTodoDialog() {
        DialogAddTodoBinding dialogBinding = DialogAddTodoBinding.inflate(getLayoutInflater());
        Log.d("TodoActivity", "进入对话框");
        // 设置提醒按钮点击事件
        dialogBinding.btnSetReminder.setOnClickListener(v -> {
            Log.d("TodoActivity", "设置提醒按钮被点击");
            showDateTimePicker();
        });

        new AlertDialog.Builder(this)
                .setTitle("添加待办事项")
                .setView(dialogBinding.getRoot())
                .setPositiveButton("完成", (dialog, which) -> {
                    String newTodo = dialogBinding.editTextTodo.getText().toString().trim();
                    if (!newTodo.isEmpty()) {
                        // 如果用户选择了设置提醒，则存储提醒时间
                        if (reminderTime != -1) {
                            setReminder(newTodo, reminderTime);
                        }

                        // 添加待办事项到数据库
                        databaseHelper.addTodo(newTodo);
                        loadTodoList(); // 重新加载待办事项
                        dialog.dismiss(); // 确保对话框关闭
                    } else {
                        Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                .show();
    }

    // 弹出日期选择器
    private void showDateTimePicker() {
        Calendar calendar = Calendar.getInstance();
        Log.d("TodoActivity", "进入日期选择器");
        // 日期选择器
        new android.app.DatePickerDialog(
                TodoActivity.this,
                (view, year, month, dayOfMonth) -> {
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, month);
                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    // 显示时间选择器
                    showTimePicker(calendar);
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        ).show();
    }

    // 弹出时间选择器
    private void showTimePicker(Calendar calendar) {
        // 时间选择器
        new android.app.TimePickerDialog(
                TodoActivity.this,
                (view, hourOfDay, minute) -> {
                    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    calendar.set(Calendar.MINUTE, minute);
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 0);
                    reminderTime = calendar.getTimeInMillis();  // 获取最终的提醒时间

                    // 这里可以加一个日志输出，确认 reminderTime 是否被正确赋值
                    Log.d("TodoActivity", "设置提醒时间为: " + reminderTime);
                    Toast.makeText(this, "提醒时间设置为: " + reminderTime, Toast.LENGTH_SHORT).show();
                },
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
        ).show();
    }
    // 设置提醒
    public void setReminder(String todo, long reminderTime) {
        if (reminderTime == -1) {
            Toast.makeText(this, "提醒时间未设置", Toast.LENGTH_SHORT).show();
            Log.d("TodoActivity", "提醒时间未设置，无法继续设置提醒");
            return;
        }

        if (reminderTime <= System.currentTimeMillis()) {
            Toast.makeText(this, "请选择一个未来的时间", Toast.LENGTH_SHORT).show();
            Log.d("TodoActivity", "设置提醒失败：选择的时间不是未来时间，当前时间: " + System.currentTimeMillis() + ", 提醒时间: " + reminderTime);
            return;
        }

        // 检查 API 级别和权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            if (alarmManager != null && !alarmManager.canScheduleExactAlarms()) {
                Intent intent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
                startActivity(intent);
                Toast.makeText(this, "请在设置中开启精确闹钟权限", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        // 计算从当前时间到提醒时间的延迟时间
        long delay = reminderTime - System.currentTimeMillis();
        Log.d("TodoActivity", "准备设置提醒，待办事项: " + todo + ", 提醒时间: " + reminderTime + ", 当前时间: " + System.currentTimeMillis());

        // 创建用于发送广播的 Intent
        Intent intent = new Intent(this, ReminderBroadcastReceiver.class);
        intent.putExtra("todo", todo);

        // 使用 PendingIntent.FLAG_IMMUTABLE 或 FLAG_MUTABLE 根据需要
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int) reminderTime, intent, PendingIntent.FLAG_IMMUTABLE);

        // 获取 AlarmManager 系统服务
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        if (alarmManager != null) {
            // 使用 setExactAndAllowWhileIdle 而不是 setExact
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, reminderTime, pendingIntent);
            Toast.makeText(this, "提醒已设置", Toast.LENGTH_SHORT).show();
            Log.d("TodoActivity", "提醒已成功设置，待办事项: " + todo + ", 提醒时间: " + reminderTime);
        } else {
            Toast.makeText(this, "无法设置提醒，请检查权限", Toast.LENGTH_SHORT).show();
            Log.d("TodoActivity", "无法获取 AlarmManager 服务！");
        }
    }

}
